package com.zimmur.interceptor;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.filter.OncePerRequestFilter;

public class ResuleApiFilter extends OncePerRequestFilter{

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		// 不过滤的uri  
        String[] notFilter = new String[] { "login.html", "index.html" };  
  
        // 请求的uri  
        String uri = request.getRequestURI();
        
     // uri中包含restful时才进行过滤  
        if (uri.indexOf("restful") != -1) {  
        	 // 是否过滤  
            boolean doFilter = true;  
            for (String s : notFilter) {  
                if (uri.indexOf(s) != -1) {  
                    // 如果uri中包含不过滤的uri，则不进行过滤  
                    doFilter = false;  
                    break;  
                }  
            }  
            if (doFilter) {
            	// 执行过滤  
                // 从param中获取登录者实体  
                Object obj = request.getAttribute("token");
                if (null == obj) {  
                	 // 设置request和response的字符集，防止乱码  
                    request.setCharacterEncoding("UTF-8");  
                    response.setCharacterEncoding("UTF-8");  
                    PrintWriter out = response.getWriter();
                    StringBuilder builder = new StringBuilder(); 
                    builder.append("{code:401,message:'not token'}");
                    
                    out.print(builder.toString());  
                }else {  
                    // 如果param中存在登录者实体，则继续  
                    filterChain.doFilter(request, response);  
                } 
            }
        }else {  
            // 如果uri中不包含restful，则继续  
            filterChain.doFilter(request, response);  
        }  
	}

}
